<?php
declare(strict_types = 1);
namespace  plugin\banmitongcheng\api;

use app\banmi\common\Basehome;
use think\facade\Db;
use app\api\service\UploadService;
use think\exception\ValidateException;
use think\facade\Validate;
use think\facade\Log;
use think\facade\Filesystem;
use app\banmi\dispatch\UserDispatch;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Contract\HttpClientInterface;

class Indexv1 extends Basehome
{
    public $NotLogin=["home_index","mp_wx_login"];
    
    
    public function define_str_replace($data)
    {
        return str_replace(' ', '+', $data);
    }
   
    public function home_index()
    {
        $list =  Db::name('plugin_banmitongcheng_home_nav')->where('start', 0)->where('status', 2)->select();
        $data['list']=$list;
        ajaxmsg('ok', 200, $data);
    }
  

    
 
    //v1 入住付款版
    public function index()
    {
        $find = Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
        $buy_list = Db::name('plugin_banmitongcheng_voen_pay')->where('start', 1)->select();
        $buy_list = $buy_list->all();
        foreach ($buy_list as $key => $value) {
            $buy_list[$key]['is_ture'] = false;
        }
        $buy_list[0]['is_ture'] = true;
        $data['find'] = $find;
        $data['buy_list'] = $buy_list;
        ajaxmsg('ok', 200, $data);
    }
    
    //公众号支付
    public function pay_h5()
    {
        $pay_v2 = new \banmi\Apimpweixinv2();
        $find = Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
      
        $mch_id = $find['wx_mch_id'];//微信支付商户id
        $key = $find['wx_mch_key'];//微信支付商户秘钥
        $appId='wxf73d5a1dab77980e';//公众号id
        $secret='3c914bf773f0d12219f54abda8e55f5b';//公众号secret
        $openid='65465486548';
        $out_trade_no=time();
        $total_amount=1;
        $desc='65489';
        $notify_url='https://tp6.banmiquan.com/plugin.php/bantongchengshop.Indexv1/pay_h5?code=564';
        $return = $pay_v2->wxpay($appId, $mch_id, $key, $secret, $desc, $openid, $out_trade_no, $total_amount, $notify_url);
        $return = json_decode($return, true);
    }
    
    
    
    
    //小程序支付
    public function pay_code()
    {
        $uid = is_login();
        $code = input('request.code');
        $find = Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
        $appid = $find['wx_appid'];
        $secret = $find['wx_secret'];
        if (!$appid) {
            ajaxmsg('请设置小程序appid', 0);
        }
        if (!$secret) {
            ajaxmsg('请设置小程序secret', 0);
        }
        if (!$find['wx_mch_id']) {
            ajaxmsg('请设置微信商户mch_id', 0);
        }
        if (!$find['wx_mch_key']) {
            ajaxmsg('请设置微信商户key秘钥', 0);
        }
 
        $data = $this->weixin_code($code);
        if (!empty($data['errcode'])) {
            ajaxmsg('ok', 1, $data);
        }
        $this->weixin_payaa($data['openid'], $uid);
    }
    private function weixin_code($code)
    {
        $find = Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
        $appid = $find['wx_appid'];
        $secret = $find['wx_secret'];
            
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code=" . $code;
        $data = http_curl($url);
        if (!empty($data['errcode'])) {
            ajaxmsg('ok', 1, $data);
        }
        return $data;
    }
    
    private function weixin_payaa($openid, $uid)
    {
        $find = Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
        $appid = $find['wx_appid'];
        $mch_id = $find['wx_mch_id'];
        $key = $find['wx_mch_key'];
        $voen_pay_id = input('request.id');
   
        $type = input('request.type', 0);
        if ($type==0) {//入住
            $find = Db::name('plugin_banmitongcheng_voen_pay')->where('id', $voen_pay_id)->find();
            if (!$find) {
                ajaxmsg('非法操作', 0);
            }
        } else {//置顶
           $voen_pay_id= input('request.top_day', 1);//置顶天数
          
           $voen_pay_id= intval($voen_pay_id);
            $find['price']=$find['top_price']*$voen_pay_id;
            $find['price']=$find['price'];
            $find['name']='商家电话置顶';
        }
          
        
        
        //创建订单
        $out_trade_no = rand(100000000, 999999999) . time();
        $id = Db::name('plugin_banmitongcheng_shop_pay')->save(['time' => time(), 'order' => $out_trade_no, 'voen_pay_id' => $voen_pay_id, 'pay_type' => 1, 'uid' => $uid   , 'type' => $type ]);
        if (!$id) {
            ajaxmsg('创建订单失败,请联系客服', 0);
        }
        $total_fee = $find['price'];
        $body = $find['name'];
        $total_fee = floatval($total_fee);
        $pay_v2 = new \banmi\Apiwechatv2();
        $notify_url =home_url().'/plugin.php/bantongchengshop.Indexv1/notify';
        $return = $pay_v2->weixinapp($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $notify_url);
        $return = json_encode($return);
        $return = json_decode($return);
        ajaxmsg('ok', 200, $return);
    }
    public function notify()
    {
        //接收微信参数
        $postXml = file_get_contents("php://input"); //接收微信参数
        Log::write($postXml);
        if (empty($postXml)) {
            return false;
        } else {
            $pay_v2 = new \banmi\Apiwechatv2();
            $paypost = $pay_v2->xmlToArray($postXml); //微信传递回来的参数，做详细判断
            if ($paypost['return_code'] == 'SUCCESS') {
                $find = Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
                $mch_id = $find['wx_mch_id'];
                if ($paypost['mch_id']!=$mch_id) {
                    return false;
                }
                
                
                Db::startTrans();
                //悲观锁
                try {
                    $map['order'] = $paypost['out_trade_no'];
                    $map['is_pay'] = 0;
                    $find = Db::name('plugin_banmitongcheng_shop_pay')->lock(true)->where($map)->find();
                    if ($find) { //验证成功 通过vip
                
                        $shop_find = Db::name('plugin_banmitongcheng_shop_list')->where('uid', $find['uid'])->find();
                        if ($find['type']==0) {//入驻
                            $find_lei = Db::name('plugin_banmitongcheng_voen_pay')->where('id', $find['voen_pay_id'])->find();
                            $day=$find_lei['day'];
                            $end_time=$shop_find['vip_end_time'];
                        } else {//置顶
                            $day=$find['voen_pay_id'];
                            $end_time=$shop_find['top_end_time'];
                        }
                    
                        $time = time();
                        if ($end_time > $time) { //会员未过期or置顶没过期
                            $time =$end_time;
                        }
                        $vip_end_time = $time + $day * 86400;
                    
                        if ($find['type']==0) {
                            $data_shop['vip_end_time']=$vip_end_time;
                        } else {
                            $data_shop['top_end_time']=$vip_end_time;
                        }
 
                        $up = Db::name('plugin_banmitongcheng_shop_list')->where('uid', $find['uid'])->data($data_shop)->update();
                        $up = Db::name('plugin_banmitongcheng_shop_pay')->where($map)->data([
                        'is_pay' => 1,
                        'transaction_id' => $paypost['transaction_id'],
                        'total_fee' => $paypost['total_fee']
                        ])->update();
                        
                        Db::commit();
                        echo 'SUCCESS';
                    }
                } catch (Exception $ex) {
                    Db::rollback();
                    return false;
                }
            }
        }
    }
}
